/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.services;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import utsc.apps.utschedule.classes.Assignment;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.format.Time;

/**
 * This receiver is used to listen for the boot event. During the boot event, we
 * will try to setup the alarm for all the assignments because all the alarms we
 * previously set are gone after re-boot.
 * 
 */
public class BootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// in our case intent will always be BOOT_COMPLETED, so we can just set
	    // the alarm
	    // Note that a BroadcastReceiver is *NOT* a Context. Thus, we can't use
	    // "this" whenever we need to pass a reference to the current context.
	    // Thankfully, Android will supply a valid Context as the first parameter
	    
		new SetupAlarmTask(context).execute();
	}
	
	private static class SetupAlarmTask extends AsyncTask<Void, Void, List<Course>>{

		Context _context;
		public SetupAlarmTask(Context context){
			this._context=context;
		}
			
		@Override
		protected List<Course> doInBackground(Void... params) {
			final DatabaseManager manager=DatabaseManager.getInstance(_context);
		   
			Timetable activeTimetable=manager.getCurrentActiveTimetable();
		    if (activeTimetable!=null) {
		    	return manager.getCoursesWithoutTutorials(activeTimetable.get_timetableID());
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(List<Course> courses) {
			if (courses!=null && !courses.isEmpty()) {
				AlarmManager am = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
				Time now=new Time();
				now.setToNow();
				now.second=0;
				now.normalize(false);
				for (Course course : courses) {
					ArrayList<Assignment> assignments=course.get_assignmentList();
					if (assignments!=null) {
						
						for (Assignment assignment : assignments) {
							//Log.i("bootreceiver",assignment.get_AssUID()+"");
							String datetime=assignment.get_DueDate()+" "+assignment.get_DueTime();
							Calendar calendar=TimetableHelper.convertFromDateTimeString(datetime, TimetableHelper.TYPE_DATETIME);
							calendar.add(Assignment.REMINDER_LIST[assignment.get_reminderUnit()], -(assignment.get_reminder()));
							long d=calendar.getTimeInMillis();
							Time t=new Time();
							t.set(d);
							if (t.after(now)) {
								Intent intent1 = new Intent(_context, NotifyService.class);
						        intent1.putExtra(NotifyService.INTENT_NOTIFY, true);
						        intent1.setData(Uri.parse("assignment:"+assignment.get_AssUID()));
						        PendingIntent pendingIntent = PendingIntent.getService(_context, 0, intent1, 0);
						        am.cancel(pendingIntent);
						        am.set(AlarmManager.RTC, d, pendingIntent);
							}
						}
					}
					
				}
			}
			DatabaseManager.release();
		}
		
	}
	

}
